// 显示添加到分组对话框
function showAddToGroupDialog(stockCode, stockName) {
    const groupSelect = $('<select class="form-select mb-3" id="groupSelect"></select>');

    $.ajax({
        url: '/stockGroup/groupList',
        method: 'GET',
        success: function (res) {
            if (res.code === "0000") {
                res.data.forEach(group => {
                    groupSelect.append(`<option value="${group.id}">${group.name}</option>`);
                });

                const dialog = $(`
                    <div class="modal fade" id="addToGroupModal" tabindex="-1">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">添加股票到分组</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <p>将股票 <strong>${stockName}</strong> 添加到以下分组：</p>
                                    ${groupSelect.prop('outerHTML')}
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                    <button type="button" class="btn btn-primary" id="confirmAddBtn">确认添加</button>
                                </div>
                            </div>
                        </div>
                    </div>
                `);

                $('body').append(dialog);
                $('#addToGroupModal').modal('show');

                // 确认添加按钮事件
                $('#confirmAddBtn').click(function () {
                    const groupId = $('#groupSelect').val();
                    addStockToGroup(stockCode, stockName, groupId);
                    $('#addToGroupModal').modal('hide');
                });

                // 模态框关闭后销毁
                $('#addToGroupModal').on('hidden.bs.modal', function () {
                    $(this).remove();
                });
            }
        }
    });
}

// 添加股票到分组
function addStockToGroup(stockCode, stockName, groupId) {
    const data = {
        stockCode: stockCode,
        name: stockName,
        groupId: groupId
    };
    $.ajax({
        url: `/stockGroup/addToGroup`,
        method: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: function (res) {
            if (res.code === "0000") {
                showToast('股票已添加到分组', 'success');
                // 如果当前正在查看这个分组，则刷新显示
                if (currentGroupId == groupId) {
                    loadGroupStocks(groupId);
                }
            } else {
                showToast('添加失败: ' + res.msg, 'error');
            }
        },
        error: function () {
            showToast('网络错误，请重试', 'error');
        }
    });
}

// 加载分组列表
function loadGroupList() {
    $.ajax({
        url: '/stockGroup/groupList',
        method: 'GET',
        success: function (res) {
            if (res.code === "0000") {
                displayGroupList(res.data);
            }
        }
    });
}

// 显示分组列表
function displayGroupList(groups) {
    const container = $('#groupList');
    container.empty();

    groups.forEach(group => {
        const groupItem = $(`
            <div class="list-group-item d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="mb-1 group-name" style="cursor: pointer;" 
                        data-group-id="${group.id}" 
                        data-group-name="${group.name}">${group.name}</h6>
                    <small class="text-muted">${group.description || ''}</small>
                </div>
                <div>
                    <button class="btn btn-sm btn-outline-primary edit-group-btn me-1" 
                            data-group-id="${group.id}" 
                            data-group-name="${group.name}" 
                            data-group-description="${group.description || ''}">编辑</button>
                    <button class="btn btn-sm btn-outline-danger delete-group-btn" 
                            data-group-id="${group.id}" 
                            data-group-name="${group.name}">删除</button>
                </div>
            </div>
        `);

        container.append(groupItem);
    });

    // 绑定分组名称点击事件（查看分组中的股票）
    $('.group-name').click(function () {
        const groupId = $(this).data('group-id');
        const groupName = $(this).data('group-name');
        currentGroupId = groupId;
        $('#currentGroupName').text(groupName);
        $('#flushListBut').val(groupId);
        loadGroupStocks(groupId);
    });

    // 刷新列表
    $('#flushListBut').click(function () {
        const groupId = $('#flushListBut').val();
        loadGroupStocks(groupId);
    });

    // 后台开关
    $('#flushFlagBut').click(function () {
        $.ajax({
            url: `/api/stock/isFlush`,
            method: 'GET',
            success: function (res) {
                if (res.code === "0000") {
                    showToast(res.data, 'info');
                }
            }
        });
    });

    // 绑定编辑分组按钮事件
    $('.edit-group-btn').click(function () {
        const groupId = $(this).data('group-id');
        const groupName = $(this).data('group-name');
        const groupDescription = $(this).data('group-description');

        $('#editGroupId').val(groupId);
        $('#editGroupName').val(groupName);
        $('#editGroupDescription').val(groupDescription);
        $('#editGroupModal').modal('show');
    });

    // 绑定删除分组按钮事件
    $('.delete-group-btn').click(function () {
        const groupId = $(this).data('group-id');
        const groupName = $(this).data('group-name');

        if (confirm(`确定要删除分组 "${groupName}" 吗？`)) {
            deleteGroup(groupId);
        }
    });
}

// 删除分组
function deleteGroup(groupId) {
    $.ajax({
        url: `/stockGroup/deleteGroup/${groupId}`,
        method: 'DELETE',
        success: function (res) {
            if (res.code === "0000") {
                loadGroupList();
                // 如果删除的是当前查看的分组，清空股票列表
                if (currentGroupId == groupId) {
                    currentGroupId = null;
                    $('#currentGroupName').text('请选择分组');
                    $('#groupStocksTable').empty();
                }
                showToast('分组删除成功', 'success');
            } else {
                showToast('删除失败: ' + res.msg, 'error');
            }
        },
        error: function () {
            showToast('网络错误，请重试', 'error');
        }
    });
}